﻿using System;
using ZX.Web.UI.Controls;
using ZX.SYS.Bussiness;
using System.Data;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Text;
using System.IO;
using System.Xml;
using System.Net;
namespace ZX.WebApp.Message
{
    public partial class MmsSend : BasePage
    {
        public static readonly string fileurl = ConfigurationManager.AppSettings["filepath"].ToString();
        public static readonly string mmsUname = ConfigurationManager.AppSettings["mmsUname"].ToString();
        public static readonly string mmsUpass = ConfigurationManager.AppSettings["mmsUpass"].ToString();
        protected void Page_Load(object sender, EventArgs e)
        {
            this._fileCodeType = Encoding.Default.HeaderName;
            this._sendAdress = ConfigurationManager.AppSettings["SendURL"].ToString();//SendURL
        }
        protected void btnsendOnClick(object sender, EventArgs e)
        {
            string userid = PM.Value;
            string userp="";
            string users = txtPM.Value;
            string messa = txtMODEL.Value;
            string mmsid = MODEL.Value;
           
            if (messa.Length > 30)
            {
                Labmes.Text = "字数限制：彩信标题字数超过30，请返回彩信仓库修改后再选择！";
                return;
            }
            string op = selectOption.SelectedValue;
            ZX.SYS.Bussiness.MQproccess mqp = new ZX.SYS.Bussiness.MQproccess();
            string back = "";
            StringBuilder sbu = new StringBuilder();
            if (op == "2" && userid != "")//号码准备
            {
                DataTable dt = mqp.GetUserType(userid);
                DataRow[] dr = dt.Select();
                if (dr.Length > 0)
                {
                    for (int i = 0; i < dr.Length; i++)
                    {
                        if (dr[i]["ShouJi"].ToString()!="")
                            sbu.Append(dr[i]["ShouJi"].ToString()+"_"+ dr[i]["Xing"].ToString() + ",");
                    }
                }
                else
                {
                    back += "该组无成员，无法发送!";
                    users = "";//后面不再执行430424198703018215
                    return;
                }
                userp = sbu.ToString().Substring(0,sbu.ToString().Length-1);
            }
            else if (users != "" && users != string.Empty)
            {
                userp = users; //Regex.Replace(users, "<[^> ]*>", "");
            }

            MmsProccess mp = new MmsProccess();
            string fname = mp.getmmsfilename(mmsid);

            if (fname != "")
            {
                //2014-4-21 获取文本内容
                string txt1 = "";
                if (File.Exists(Server.MapPath(fileurl + fname + "/1.txt")))
                {
                    StreamReader sr = new StreamReader(Server.MapPath(fileurl + fname + "/1.txt"));///StreamReader sr = new StreamReader("TestFile.txt",Encoding.GetEncoding("GB2312"))
                    String line;
                    StringBuilder sb = new StringBuilder();
                    while ((line = sr.ReadLine()) != null)
                    {
                        txt1 += line.ToString() + "\r\n";
                    }
                    //发送彩信
                    back += sendMms(mmsid,fname,userp,txt1);
                }
                else
                {
                    back += "无法找到首贞文本";
                } 
            }
            else
                back += "数据库中无该彩信记录！";

            Labmes.Text = back;
        }


        public string sendMms(string mmsid,string fname, string userp, string utext)
        {
            string back = "";
            string newxml = "";
            string[] usernum=userp.Split(',');
            for (int i = 0; i < usernum.Length; i++)
            {
                string phone = "";
                string xing = "";
                if (usernum[i].Contains("_"))
                {
                    phone = usernum[i].Split('_')[0];
                    xing = usernum[i].Split('_')[1];
                }
                else
                {
                    phone = usernum[i].Split('>')[1];
                    xing = usernum[i].Substring(1,1);
                }

                if (File.Exists(Server.MapPath(fileurl + fname + "/1.xml")))
                {
                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.Load(Server.MapPath(fileurl + fname + "/1.xml"));
                    XmlNode root = xmldoc.SelectSingleNode("Body");

                    XmlElement acc = xmldoc.CreateElement("", "account", "");
                    acc.InnerText = mmsUname;
                    XmlElement apw = xmldoc.CreateElement("", "password", "");
                    apw.InnerText = mmsUpass;
                    root.PrependChild(apw);
                    root.PrependChild(acc);
                    //-----2014-4-21新增
                    XmlNode mms = root.SelectSingleNode("mms");
                    XmlElement phs = xmldoc.CreateElement("", "phonelist", "");
                    phs.InnerText = phone; //phs.InnerText = userp;
                    mms.PrependChild(phs);

                    XmlNode pages1 = mms.SelectSingleNode("pages/page[@order='1']");
                    XmlElement text = xmldoc.CreateElement("", "text", "");
                    text.SetAttribute("type", "txt");
                    text.InnerText = EncodeBase64("GBK", utext.Replace("{姓}",xing));
                    pages1.AppendChild(text);
                    //创建发送文件夹 XmlNode node = xmlDoc.SelectSingleNode("aasman/makeannc/field[@name='zone_maps']");
                    if (!Directory.Exists(Server.MapPath(fileurl + "hadSended")))
                    {
                        Directory.CreateDirectory(Server.MapPath(fileurl + "hadSended"));
                    }
                    //保存创建好的XML文档  
                    string xmlfilename = phone + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xml";
                    string xmlbackname = phone + DateTime.Now.ToString("yyyyMMddHHmmss") + "_back.xml";
                    newxml = Server.MapPath(fileurl + "hadSended1/" + xmlfilename);

                    //xmldoc.Save(newxml);
                    //保存创建好的XML文档   
                    using (XmlTextWriter xtw = new XmlTextWriter(newxml, null))
                    {
                        xtw.Formatting = Formatting.None;
                        xmldoc.Save(xtw);
                    }
                    //读取XML
                    System.IO.StreamReader sr = new System.IO.StreamReader(newxml, Encoding.GetEncoding(this._fileCodeType));
                    string stra = sr.ReadToEnd();
                    //转换成UTF8格式/////////////////////////////////////////////////////////////////////////////////////////
                    byte[] convertbyte = Encoding.GetEncoding(this._fileCodeType).GetBytes(stra);
                    byte[] tempbyte = Encoding.Convert(Encoding.GetEncoding(this._fileCodeType), Encoding.UTF8, convertbyte);
                    string convertstring = Encoding.UTF8.GetString(tempbyte);
                    //string b64Stra = EncodeBase64("UTF-8", convertstring);

                    string xmlback = "";
                    try
                    {
                        xmlback = PostXml(this._sendAdress, convertstring);//发送
                    }
                    catch (Exception ex)
                    {
                        back += "发送时出错，错误为：" + ex.Message;
                    }
                    if (xmlback != "")
                    {
                        XmlDocument xmlbc = new XmlDocument();
                        xmlbc.LoadXml(xmlback);
                        XmlNode bd = xmlbc.SelectSingleNode("Body");
                        XmlNode sbstatus = bd.SelectSingleNode("submitstatus");
                        XmlNode sbmsgid = bd.SelectSingleNode("servermsgid");
                        string sbstauts = sbstatus.InnerText;
                        if (sbstauts == "0000")
                        {
                            back += "发送成功！";
                            try
                            {

                                MmsProccess mmpr = new MmsProccess();
                                mmpr.insertMmsSend(this.User.UserID, mmsid, userp, xmlfilename, xmlbackname, "成功", sbmsgid.InnerText);
                            }
                            catch (Exception ex)
                            {
                                back += "成功信息插入数据库出错，错误信息为：" + ex.Message;
                            }
                        }
                        else
                        {
                            back += "发送失败！错误码为：" + sbstauts;
                        }
                        xmlbc.Save(Server.MapPath(fileurl + "hadSended2/" + xmlbackname));
                    }
                    else
                    {
                        back += "发送后无返回了XML结果";
                    }

                }
                else
                {
                    back += "编辑文件中找不到XML文件！";
                }
            }
            return back;
        }

        private string _fileCodeType;
        private string _sendAdress;

        #region 属性
        /// <summary>
        /// 待发送文件的编码
        /// </summary>
        public string FileCodeType
        {
            get
            {
                return _fileCodeType;
            }
            set
            {
                _fileCodeType = value;
            }
        }
        /// <summary>
        /// 发送地址的URI
        /// </summary>
        public string SendAdress
        {
            get
            {
                return _sendAdress;
            }
            set
            {
                _sendAdress = value;
            }
        }
        #endregion
        public string PostXml(string url, string strPost)
        {
            string result = "";

            StreamWriter myWriter = null;
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
            objRequest.Method = "POST";
            //objRequest.ContentLength = strPost.Length;
            objRequest.ContentType = "text/xml";//提交xml 
            //objRequest.ContentType = "application/x-www-form-urlencoded";//提交表单
            try
            {
                myWriter = new StreamWriter(objRequest.GetRequestStream());
                myWriter.Write(strPost);
            }
            catch (Exception e)
            {
                return e.Message;
            }
            finally
            {
                myWriter.Close();
            }

            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
            {
                result = sr.ReadToEnd();
                sr.Close();
            }
            return result;
        }

        #region Base64编码与解码
        /// <summary>
        /// Base64编码
        /// </summary>
        /// <param name="code_type">字符串编码类型</param>
        /// <param name="code">需要Base64编码的字符串</param>
        /// <returns>经过Base64编码的字符串</returns>
        private string EncodeBase64(string code_type, string code)
        {
            string encode = "";
            byte[] bytes = System.Text.Encoding.GetEncoding(code_type).GetBytes(code);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = code;
            }
            return encode;
        }

        /// <summary>
        /// Base64解码
        /// </summary>
        /// <param name="code_type">字符串解码类型</param>
        /// <param name="code">需要Base64解码的字符串</param>
        /// <returns>经过Base64解码的字符串</returns>
        private string DecodeBase64(string code_type, string code)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(code);
            try
            {
                decode = Encoding.GetEncoding(code_type).GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }


        #endregion
    }
}